package DBSystem;


import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.LayoutStyle;
import javax.swing.SwingConstants;

import javax.swing.WindowConstants;
import javax.swing.SwingUtilities;


/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class ClientGUI extends javax.swing.JFrame {
	private JButton jButtonSend;
	private JButton jButtonClose;
	private JLabel jLabel2;
	private JButton jButtonToggleConnection;
	private AbstractAction actionSend;
	private AbstractAction actionCancelDialog;
	private AbstractAction actionDoConnect;
	private AbstractAction actionOpenDialog;
	private JButton jButtonCancel;
	private JButton jButtonConHost;
	private JTextField jTextFieldHostPort;
	private JLabel jLabelHostPort;
	private JTextField jTextFieldHostAddress;
	private JLabel jLabelHostAddress;
	private JDialog jDialogConnect;
	private JLabel jLabelReceive;
	private JPanel jPanel2;
	private JPanel jPanel1;
	private AbstractAction actionClose;
	private JComboBox jComboBoxCmdList;
	private JTextField jTextFieldCommand;
	private JLabel jLabel1;
	
	private ClientSocket clientSocket;
	private boolean isConnected = false;
	private String[] commandList = {"CREATE TABLE testtabelle (INT attr1, CHAR attr2);", "INSERT INTO testtabelle (attr1, attr2) VALUES (45,  p);", "SELECT * FROM testtabelle;","DROP TABLE testtabelle;"};

	/**
	* Auto-generated main method to display this JFrame
	*/
	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				ClientGUI inst = new ClientGUI();
				inst.setLocationRelativeTo(null);
				inst.setVisible(true);
			}
		});
	}
	
	public ClientGUI() {
		super();
		initGUI();
		initClient();
	}
	
	private void initClient() {
		// TODO Auto-generated method stub
		
	}

	private void initGUI() {
		try {
			setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
			GroupLayout thisLayout = new GroupLayout((JComponent)getContentPane());
			getContentPane().setLayout(thisLayout);
			this.setTitle("DB-System Project -- Client GUI");
			{
				jButtonClose = new JButton();
				jButtonClose.setText("Close");
				jButtonClose.setAction(getActionClose());
			}
			thisLayout.setVerticalGroup(thisLayout.createSequentialGroup()
				.addContainerGap()
				.addComponent(getJPanel1(), GroupLayout.PREFERRED_SIZE, 143, GroupLayout.PREFERRED_SIZE)
				.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
				.addComponent(getJPanel2(), 0, 77, Short.MAX_VALUE)
				.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
				.addGroup(thisLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
				    .addComponent(getJButtonToggleConnection(), GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
				    .addComponent(jButtonClose, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE))
				.addContainerGap());
			thisLayout.setHorizontalGroup(thisLayout.createSequentialGroup()
				.addContainerGap()
				.addGroup(thisLayout.createParallelGroup()
				    .addGroup(GroupLayout.Alignment.LEADING, thisLayout.createSequentialGroup()
				        .addComponent(getJButtonToggleConnection(), GroupLayout.PREFERRED_SIZE, 125, GroupLayout.PREFERRED_SIZE)
				        .addGap(0, 191, Short.MAX_VALUE)
				        .addComponent(jButtonClose, GroupLayout.PREFERRED_SIZE, 125, GroupLayout.PREFERRED_SIZE)
				        .addGap(6))
				    .addComponent(getJPanel1(), GroupLayout.Alignment.LEADING, 0, 447, Short.MAX_VALUE)
				    .addComponent(getJPanel2(), GroupLayout.Alignment.LEADING, 0, 447, Short.MAX_VALUE))
				.addContainerGap());
			thisLayout.linkSize(SwingConstants.HORIZONTAL, new Component[] {getJButtonToggleConnection(), jButtonClose});
			pack();
			this.setSize(471, 299);
		} catch (Exception e) {
		    //add your error handling code here
			e.printStackTrace();
		}
	}
	
	private AbstractAction getActionClose() {
		if(actionClose == null) {
			actionClose = new AbstractAction("Close", null) {
				public void actionPerformed(ActionEvent evt) {
					//TODO: close socket and stuff
					System.exit(0);		}
			};
		}
		return actionClose;
	}
	
	private JButton getJButtonToggleConnection() {
		if(jButtonToggleConnection == null) {
			jButtonToggleConnection = new JButton();
			jButtonToggleConnection.setText("Connect");
			jButtonToggleConnection.setAction(getActionOpenDialog());
		}
		return jButtonToggleConnection;
	}
	
	private JPanel getJPanel1() {
		if(jPanel1 == null) {
			jPanel1 = new JPanel();
			GroupLayout jPanel1Layout = new GroupLayout((JComponent)jPanel1);
			jPanel1.setLayout(jPanel1Layout);
			jPanel1.setBorder(BorderFactory.createTitledBorder("Send"));
			{
				jLabel1 = new JLabel();
				jLabel1.setText("Enter SQL-command here:");
			}
			{
				jTextFieldCommand = new JTextField();
				jTextFieldCommand.setText("<SQL Command>");
			}
			{
				jLabel2 = new JLabel();
				jLabel2.setText("Or choose from this list of commands:");
			}
			{
				ComboBoxModel jComboBoxCmdListModel = 
					new DefaultComboBoxModel(commandList);
				jComboBoxCmdList = new JComboBox();
				jComboBoxCmdList.setModel(jComboBoxCmdListModel);
				jComboBoxCmdList.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent evt) {
						jComboBoxCmdListActionPerformed(evt);
					}
				});
			}
			{
				jButtonSend = new JButton();
				jButtonSend.setText("Send");
				jButtonSend.setAction(getActionSend());
			}
			jPanel1Layout.setHorizontalGroup(jPanel1Layout.createSequentialGroup()
				.addContainerGap()
				.addGroup(jPanel1Layout.createParallelGroup()
				    .addComponent(jLabel1, GroupLayout.Alignment.LEADING, 0, 413, Short.MAX_VALUE)
				    .addComponent(jTextFieldCommand, GroupLayout.Alignment.LEADING, 0, 413, Short.MAX_VALUE)
				    .addComponent(jLabel2, GroupLayout.Alignment.LEADING, 0, 413, Short.MAX_VALUE)
				    .addGroup(GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
				        .addComponent(jComboBoxCmdList, GroupLayout.PREFERRED_SIZE, 219, GroupLayout.PREFERRED_SIZE)
				        .addGap(0, 107, Short.MAX_VALUE)
				        .addComponent(jButtonSend, GroupLayout.PREFERRED_SIZE, 87, GroupLayout.PREFERRED_SIZE)))
				.addContainerGap());
			jPanel1Layout.setVerticalGroup(jPanel1Layout.createSequentialGroup()
				.addComponent(jLabel1, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
				.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
				.addComponent(jTextFieldCommand, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
				.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
				.addComponent(jLabel2, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
				.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, 0, Short.MAX_VALUE)
				.addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
				    .addComponent(jComboBoxCmdList, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE)
				    .addComponent(jButtonSend, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE))
				.addGap(7));
		}
		return jPanel1;
	}
	
	private JPanel getJPanel2() {
		if(jPanel2 == null) {
			jPanel2 = new JPanel();
			GroupLayout jPanel2Layout = new GroupLayout((JComponent)jPanel2);
			jPanel2.setLayout(jPanel2Layout);
			jPanel2.setBorder(BorderFactory.createTitledBorder("Receive"));
			jPanel2Layout.setHorizontalGroup(jPanel2Layout.createSequentialGroup()
				.addContainerGap()
				.addComponent(getJLabelReceive(), 0, 413, Short.MAX_VALUE)
				.addContainerGap());
			jPanel2Layout.setVerticalGroup(jPanel2Layout.createSequentialGroup()
				.addComponent(getJLabelReceive(), 0, 31, Short.MAX_VALUE)
				.addContainerGap());
		}
		return jPanel2;
	}
	
	private JLabel getJLabelReceive() {
		if(jLabelReceive == null) {
			jLabelReceive = new JLabel();
			jLabelReceive.setText("<Received Data>");
		}
		return jLabelReceive;
	}
	
	private JDialog getJDialogConnect() {
		if(jDialogConnect == null) {
			jDialogConnect = new JDialog(this);
			GroupLayout jDialogConnectLayout = new GroupLayout((JComponent)jDialogConnect.getContentPane());
			jDialogConnect.getContentPane().setLayout(jDialogConnectLayout);
			jDialogConnect.setTitle("Connect to Server");
			jDialogConnect.setResizable(false);
			jDialogConnect.setUndecorated(false);
			jDialogConnect.setSize(188, 160);
			jDialogConnectLayout.setHorizontalGroup(jDialogConnectLayout.createSequentialGroup()
				.addContainerGap()
				.addGroup(jDialogConnectLayout.createParallelGroup()
				    .addComponent(getJLabelHostAddress(), GroupLayout.Alignment.LEADING, 0, 164, Short.MAX_VALUE)
				    .addComponent(getJTextFieldHostAddress(), GroupLayout.Alignment.LEADING, 0, 164, Short.MAX_VALUE)
				    .addComponent(getJLabelHostPort(), GroupLayout.Alignment.LEADING, 0, 164, Short.MAX_VALUE)
				    .addComponent(getJTextFieldHostPort(), GroupLayout.Alignment.LEADING, 0, 164, Short.MAX_VALUE)
				    .addGroup(GroupLayout.Alignment.LEADING, jDialogConnectLayout.createSequentialGroup()
				        .addComponent(getJButtonConHost(), GroupLayout.PREFERRED_SIZE, 76, GroupLayout.PREFERRED_SIZE)
				        .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED, 1, Short.MAX_VALUE)
				        .addComponent(getJButtonCancel(), GroupLayout.PREFERRED_SIZE, 76, GroupLayout.PREFERRED_SIZE)))
				.addContainerGap());
			jDialogConnectLayout.linkSize(SwingConstants.HORIZONTAL, new Component[] {getJButtonCancel(), getJButtonConHost()});
			jDialogConnectLayout.setVerticalGroup(jDialogConnectLayout.createSequentialGroup()
				.addContainerGap()
				.addComponent(getJLabelHostAddress(), GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
				.addComponent(getJTextFieldHostAddress(), GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
				.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
				.addComponent(getJLabelHostPort(), GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
				.addComponent(getJTextFieldHostPort(), GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
				.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
				.addGroup(jDialogConnectLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
				    .addComponent(getJButtonConHost(), GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
				    .addComponent(getJButtonCancel(), GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE))
				.addContainerGap());
		}
		return jDialogConnect;
	}
	
	private JLabel getJLabelHostAddress() {
		if(jLabelHostAddress == null) {
			jLabelHostAddress = new JLabel();
			jLabelHostAddress.setText("Host address:");
		}
		return jLabelHostAddress;
	}
	
	private JTextField getJTextFieldHostAddress() {
		if(jTextFieldHostAddress == null) {
			jTextFieldHostAddress = new JTextField();
			jTextFieldHostAddress.setText("localhost");
		}
		return jTextFieldHostAddress;
	}
	
	private JLabel getJLabelHostPort() {
		if(jLabelHostPort == null) {
			jLabelHostPort = new JLabel();
			jLabelHostPort.setText("Host port:");
		}
		return jLabelHostPort;
	}
	
	private JTextField getJTextFieldHostPort() {
		if(jTextFieldHostPort == null) {
			jTextFieldHostPort = new JTextField();
			jTextFieldHostPort.setText(String.valueOf(Settings.PORT));
		}
		return jTextFieldHostPort;
	}
	
	private JButton getJButtonConHost() {
		if(jButtonConHost == null) {
			jButtonConHost = new JButton();
			jButtonConHost.setText("Connect");
			jButtonConHost.setAction(getActionDoConnect());
		}
		return jButtonConHost;
	}
	
	private JButton getJButtonCancel() {
		if(jButtonCancel == null) {
			jButtonCancel = new JButton();
			jButtonCancel.setText("Cancel");
			jButtonCancel.setAction(getActionCancelDialog());
		}
		return jButtonCancel;
	}
	
	private AbstractAction getActionOpenDialog() {
		if(actionOpenDialog == null) {
			actionOpenDialog = new AbstractAction("Connect", null) {
				public void actionPerformed(ActionEvent evt) {
					if (!isConnected) {
						jDialogConnect = getJDialogConnect();
						jDialogConnect.pack();
						jDialogConnect.setLocationRelativeTo(jPanel1);
						jDialogConnect.setVisible(true);
					} else {
						clientSocket = null;
						isConnected = false;
						System.out.println("Client disconnected.");
						updateConnectButton();
					}
				}
			};
		}
		return actionOpenDialog;
	}
	
	private AbstractAction getActionDoConnect() {
		if(actionDoConnect == null) {
			actionDoConnect = new AbstractAction("Connect", null) {
				public void actionPerformed(ActionEvent evt) {
					System.out.println("Attempting to connect to server...");
					String host = jTextFieldHostAddress.getText();
					int port = 0;
					try {
						port = Integer.parseInt(jTextFieldHostPort.getText());
						clientSocket = new ClientSocket(host,port);
						isConnected = true;
						System.out.println("Connection to server established. (host: "+host+" port:"+port+")");
						updateConnectButton();
						jDialogConnect.setVisible(false);
						
					} catch (NumberFormatException nfe) {
						System.out.println("ERROR: Invalid port number!");
						nfe.printStackTrace();
					}
				}
			};
		}
		return actionDoConnect;
	}
	
	protected void updateConnectButton() {
		if (isConnected) {
			jButtonToggleConnection.setText("Disconnect");
		} else {
			jButtonToggleConnection.setText("Connect");
		}
		
	}

	private AbstractAction getActionCancelDialog() {
		if(actionCancelDialog == null) {
			actionCancelDialog = new AbstractAction("Cancel", null) {
				public void actionPerformed(ActionEvent evt) {
					updateConnectButton();
					jDialogConnect.setVisible(false);
				}
			};
		}
		return actionCancelDialog;
	}
	
	private void jComboBoxCmdListActionPerformed(ActionEvent evt) {
		jTextFieldCommand.setText((String)jComboBoxCmdList.getSelectedItem());
	}
	
	private AbstractAction getActionSend() {
		if(actionSend == null) {
			actionSend = new AbstractAction("Send", null) {
				public void actionPerformed(ActionEvent evt) {
					if (!isConnected || clientSocket == null) {
						JOptionPane.showMessageDialog(ClientGUI.this, "Client not connected yet. Please connect first.", "Client not connected", JOptionPane.WARNING_MESSAGE);
					} else {
						String cmd = jTextFieldCommand.getText();
						clientSocket.send(cmd);
						
						String answer = clientSocket.receive(); //TODO: should this be in an extra thread?
						jLabelReceive.setText(answer);
					}
				}
			};
		}
		return actionSend;
	}

}
